import { useState, useRef } from 'react';

// 自定义 Hook - useThrottle
const useThrottle = <T extends unknown[]>(callback: (...args: T) => void, delay: number) => {
  const [isThrottled, setIsThrottled] = useState(false);
  const lastExecuted = useRef(0);

  const throttledCallback = (...args: T) => {
    const now = Date.now();

    // 如果当前时间减去上次执行时间大于或等于 delay，允许执行回调
    if (!isThrottled || now - lastExecuted.current >= delay) {
      callback(...args); // 执行传入的回调函数
      lastExecuted.current = now; // 更新最后执行的时间
      setIsThrottled(true);

      // 设置一个定时器，等待延迟时间后将 isThrottled 设为 false
      setTimeout(() => {
        setIsThrottled(false);
      }, delay);
    }
  };

  return throttledCallback;
};

export default useThrottle;